package com.foolishbird.sdk.ui.fragment;

import android.app.Activity;
import android.content.Context;
import android.content.res.Configuration;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.foolishbird.sdk.core.HttpEngineApi;
import com.foolishbird.sdk.core.HttpEngineConduits;
import com.foolishbird.sdk.params.bean.AccountInfo;
import com.foolishbird.sdk.ui.assist.OnFinishActivityListener;

import java.util.List;

public class FoolishBirdLoginAutoFragment extends BaseDialogFragment implements View.OnClickListener, Handler.Callback {

    private static final int AUTO_LOGIN_MESSAGE_WHAT = 0;
    private AccountInfo mAutoLoginAccountInfo;
    private Handler mAutoLoginHandler;

    public static final FoolishBirdLoginAutoFragment newInstance() {
        return new FoolishBirdLoginAutoFragment();
    }

    @Override
    public void onAttach(@NonNull Context context) {
        super.onAttach(context);
        mAutoLoginHandler = new Handler(this);
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        HttpEngineConduits wanSDKDataDao = HttpEngineApi.getInstance().getEngineConduits();
        List<AccountInfo> accountInfos = wanSDKDataDao.readAllUserAccountInfo();
        mAutoLoginAccountInfo = accountInfos.isEmpty() ? null : accountInfos.get(0);

        if (mAutoLoginAccountInfo == null || TextUtils.isEmpty(mAutoLoginAccountInfo.getEncryptPassword())) {
//        if (mAutoLoginAccountInfo == null && TextUtils.isEmpty(mAutoLoginAccountInfo.getPassword())) {
            switchAccount();
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        super.onCreateView(inflater, container, savedInstanceState);
        View contentView = doInflateContentView(inflater, container, getLayoutIdentifier("foolishbird_fragment_login_auto"));

        TextView account = contentView.findViewById(getViewIdentifier("foolishbird_fragment_login_auto_username"));
        if (mAutoLoginAccountInfo != null) {
            account.setText(mAutoLoginAccountInfo.getUsername());
        }

        TextView switchAccount = contentView.findViewById(getViewIdentifier("foolishbird_fragment_login_auto_switch"));
        switchAccount.setOnClickListener(this);
        return contentView;
    }

    @Override
    public void onStart() {
        super.onStart();
        Configuration config = getResources().getConfiguration();
        if (Configuration.ORIENTATION_PORTRAIT != config.orientation) {
            setEnterAnimationFromTopStyle(50, true);
        } else {
            setEnterAnimationFromTopStyle(200, true);
        }

        mAutoLoginHandler.sendEmptyMessageDelayed(AUTO_LOGIN_MESSAGE_WHAT, 3500);
    }

    private OnAutoLoginActionListener getOnAutoLoginActionListener() {
        if (!isNullContext()) {
            Activity activity = getActivity();
            if (activity instanceof OnAutoLoginActionListener) {
                return (OnAutoLoginActionListener) activity;
            }
        }
        return null;
    }

    private void doAutoLogin() {
        OnAutoLoginActionListener listener = getOnAutoLoginActionListener();
        if (listener != null && mAutoLoginAccountInfo != null) {
            String username = mAutoLoginAccountInfo.getUsername();
            String password = mAutoLoginAccountInfo.getEncryptPassword();
//            String password = mAutoLoginAccountInfo.getPassword();
            listener.doAutoLoginInfo(username, password);
        }
    }

    private void switchAccount() {
        OnAutoLoginActionListener listener = getOnAutoLoginActionListener();
        if (listener != null && mAutoLoginAccountInfo != null) {
            mAutoLoginHandler.removeMessages(AUTO_LOGIN_MESSAGE_WHAT);
            listener.doFinishActivity(this);
        }
    }

    protected void setEnterAnimationFromTopStyle(int offset, boolean translucent) {
        Window window = getDialog().getWindow();
        if (window != null) {
            window.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));

            window.setWindowAnimations(getStyleIdentifier("HN669GlobalAutoDialogTheme"));

            DisplayMetrics dm = new DisplayMetrics();
            getActivity().getWindowManager().getDefaultDisplay().getMetrics(dm);

            WindowManager.LayoutParams params = window.getAttributes();
            params.gravity = Gravity.TOP;
            params.y = offset;
            params.width = ViewGroup.LayoutParams.MATCH_PARENT;
            params.height = ViewGroup.LayoutParams.WRAP_CONTENT;
            if (!translucent) {
                params.dimAmount = 0;
            }
            window.setAttributes(params);
        }
    }

    @Override
    public void onClick(View view) {
        switchAccount();
    }

    @Override
    public boolean handleMessage(@NonNull Message msg) {
        if (AUTO_LOGIN_MESSAGE_WHAT == msg.what && isResumed()) {
            doAutoLogin();
        }
        return true;
    }

    public interface OnAutoLoginActionListener extends OnFinishActivityListener {

        void doAutoLoginInfo(String username, String password);
    }
}
